package com.zhuanzhuan.hero.user.helper;

import com.zhuanzhuan.zzlock.lock.ZZEtcdLock;
import com.zhuanzhuan.zzlock.lock.ZZEtcdLockClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * ZzLockHelper
 * @author hanjunjun
 * @date 2024-6-17
 */
@Slf4j
@Component
public class ZzLockHelper implements ApplicationListener<ContextRefreshedEvent> {

    private static ZZEtcdLockClient zClient = null;

    @Value("${zzlock.ectdUrls}")
    private String ectdUrls;

    /**
     * 获取一个锁
     *
     * @param lockKey  业务场景定义的key
     * @return com.zhuanzhuan.zzlock.lock.ZZEtcdLock
     * @author  hanjunjun
     * @date 2024/6/18
     **/
    public ZZEtcdLock getLock(String lockKey) {
        return getEtcdLock("hero_user_lock_" + lockKey);
    }

    private ZZEtcdLock getEtcdLock(String lockKey) {
        log.info("lockKey={}", lockKey);
        return getZzLockClient().newLock(lockKey);
    }

    private ZZEtcdLockClient getZzLockClient() {
        if (zClient == null) {
            log.info("zClient is null");
            initZzLock();
        }
        return zClient;
    }

    private synchronized void initZzLock() {
        if (StringUtils.isBlank(ectdUrls)) {
            throw new RuntimeException("初始化ZZLock失败 缺少配置：zzlock.ectdUrls");
        }
        zClient = new ZZEtcdLockClient(ectdUrls);
        log.info("initZZLock end ...");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        log.info("init zzlock after server started! start ...");
        initZzLock();
        log.info("init zzlock after server started! end ...");
    }
}
